package cn.felord.app.util;

import cn.hutool.core.util.ArrayUtil;

import javax.servlet.http.HttpServletRequest;

import static cn.hutool.core.net.NetUtil.getMultistageReverseProxyIp;
import static cn.hutool.core.net.NetUtil.isUnknow;

/**
 * The type Ip util.
 *
 * @author dax
 */
public class IpUtil {


    private IpUtil() {
    }


    /**
     * 获取客户端IP<br>
     * 默认检测的Header：<br>
     * 1、X-Forwarded-For<br>
     * 2、X-Real-IP<br>
     * 3、Proxy-Client-IP<br>
     * 4、WL-Proxy-Client-IP<br>
     * otherHeaderNames参数用于自定义检测的Header
     *
     * @param request          请求对象
     * @param otherHeaderNames 其他自定义头文件
     * @return IP地址 string
     */
    public static String obtainClientIp(HttpServletRequest request, String... otherHeaderNames) {
        String[] headers = {"X-Forwarded-For", "X-Real-IP", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR"};
        if (ArrayUtil.isNotEmpty(otherHeaderNames)) {
            headers = ArrayUtil.addAll(headers, otherHeaderNames);
        }

        String ip;
        for (String header : headers) {
            ip = request.getHeader(header);
            if (!isUnknow(ip)) {
                return getMultistageReverseProxyIp(ip);
            }
        }

        ip = request.getRemoteAddr();
        return getMultistageReverseProxyIp(ip);
    }
}
